package com.laiyima.zhongjiang.linghuilv.demo.Serviceprovider;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.PdetailsAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.bean.PointsDetailsBean;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.view.ListViewPlus;
import com.laiyima.zhongjiang.linghuilv.demo.view.PDShadowPopupView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.SimpleCallback;

import org.json.JSONArray;
import org.json.JSONObject;
import org.wangchenlong.datescroller.widget.DateScrollerDialog;
import org.wangchenlong.datescroller.widget.data.Type;
import org.wangchenlong.datescroller.widget.listener.OnDateSetListener;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class PointsDetailsActivity extends SwipeBackActivity implements View.OnClickListener, ListViewPlus.ListViewPlusListener {
    private String TAG = "PointsDetailsActivity";
    private int dpCode;

    private LinearLayout myback, show_list_pd;
    private TextView myFind, pd_income, pd_expend,pd_time;
    private String time;
    private String day;

    private ListViewPlus mListView;
    private PointsDetailsBean mPointsDetailsBean;
    private PdetailsAdapter mPdetailsAdapter;
    private List<PointsDetailsBean> PointsDetailsBeanListBean = new ArrayList<>();
    private PDShadowPopupView popupView;

    private int page_count, page_index;
    private String type="";


    private static final long HUNDRED_YEARS = 100L * 365 * 1000 * 60 * 60 * 24L;
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM", Locale.ENGLISH);
    private long mLastTime = System.currentTimeMillis();
    private OnDateSetListener mOnDateSetListener = new OnDateSetListener() {
        @Override
        public void onDateSet(DateScrollerDialog timePickerView, long milliseconds) {
            mLastTime = milliseconds;
            time = getDateToString(milliseconds);
            //myFind.setText(time);
            find(time);
        }
    };

    @Override
    public void onRefresh() {
        PointsDetailsBeanListBean.clear();
        intView();
        mPdetailsAdapter.notifyDataSetChanged();

        loadData(ListViewPlus.REFRESH);
        // Log.e(TAG, "onRefresh:");

    }

    @Override
    public void onLoadMore() {

        if (page_index < page_count) {
            loadData(ListViewPlus.LOAD);
        } else {
            Log.e(TAG, "page_index:" + page_index);
            Toast.makeText(getBaseContext().getApplicationContext(), "已全部加载", Toast.LENGTH_SHORT).show();
            onLoadComplete();
        }
    }

    private void loadData(final int what) {
        // 这里模拟从服务器获取数据
        new Thread(new Runnable() {
            @Override
            public void run() {
//                try {
//                    Thread.sleep(2000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                Message msg = handler.obtainMessage();
                msg.what = what;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ListViewPlus.REFRESH:

                    Log.e(TAG, "onRefresh:");
                    //intView();
                    onLoadComplete();
                    Toast.makeText(getBaseContext().getApplicationContext(), "已刷新数据", Toast.LENGTH_SHORT).show();
                    break;
                case ListViewPlus.LOAD:
                    page_index++;
                    Log.e(TAG, "page_index:" + page_index);
                    loadMode(page_index, day,type);
                    break;
            }

        }

        ;
    };


    private void onLoadComplete() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
    }

    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_points_details);
        myback = (LinearLayout) findViewById(R.id.pd_back);
        myback.setOnClickListener(this);
        myFind = (TextView) findViewById(R.id.pd_find);
        myFind.setOnClickListener(this);
        pd_income = (TextView) findViewById(R.id.pd_income);
        pd_expend = (TextView) findViewById(R.id.pd_expend);
        show_list_pd = (LinearLayout) findViewById(R.id.show_list_pd);
        mListView = (ListViewPlus) findViewById(R.id.pd_list);
        mListView.setRefreshEnable(true);
        mListView.setLoadEnable(true);
        mListView.setAutoLoadEnable(true);
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
        mListView.setListViewPlusListener(this);
        pd_time= (TextView) findViewById(R.id.pd_time);
        Intent intent = getIntent();
        day = intent.getStringExtra("day");
        setStatusBar();
        intView();
    }

    private void find(String time) {
        PointsDetailsBeanListBean.clear();
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/on_day_detail");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("time", time);
        params.addBodyParameter("page_size", 10);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {


                try {
                    JSONObject jsonObject = new JSONObject(result);
                    dpCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsonObjec = new JSONObject(data);
                        page_count = jsonObjec.optInt("page_count", 0);
                        page_index = jsonObjec.optInt("page_index", 0);
                        String income = jsonObjec.optString("income", "");
                        String expend = jsonObjec.optString("expend", "");

                        String time = jsonObjec.optString("time", "");
                        String str = time.substring(0, 4);
                        String str1 = time.substring(5, 7);
                        String str2 = time.substring(8, 10);
                        pd_time.setText(str + "年" + str1 + "月"+str2+"日");


                        Double a1 = Double.parseDouble(income);
                        DecimalFormat decimalFormatq = new DecimalFormat("0.00");
                        String b1 = decimalFormatq.format(a1);
                        Double a2 = Double.parseDouble(expend);
                        String b2 = decimalFormatq.format(a2);
                        pd_income.setText(b1 + "");
                        pd_expend.setText("积分兑换   "+b2 + "");
                    }
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String uid = value.getString("uid");
                        String create_time = value.getString("create_time");
                        String wtype = value.getString("wtype");
                        String remark = value.getString("remark");
                        String money = value.getString("money");
                        mPointsDetailsBean = new PointsDetailsBean(uid, create_time, wtype, remark, money);
                        PointsDetailsBeanListBean.add(mPointsDetailsBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (dpCode == 200) {
                    //mPdetailsAdapter = new PdetailsAdapter(getBaseContext().getApplicationContext(),PointsDetailsBeanListBean);
                    // mPdetailsAdapter.notifyDataSetChanged();
                    //mListView.setAdapter(mPdetailsAdapter);
                }

                if (dpCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                } else {


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (PointsDetailsBeanListBean.size() == 0) {
                    show_list_pd.setVisibility(View.VISIBLE);
                } else {
                    show_list_pd.setVisibility(View.GONE);
                }
            }
        });
    }

    private void loadMode(int page_index, String day,String type) {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/on_day_detail");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("time", day);
        params.addBodyParameter("page_index", page_index);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("type", type);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    dpCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String uid = value.getString("uid");
                        String create_time = value.getString("create_time");
                        String wtype = value.getString("wtype");
                        String remark = value.getString("remark");
                        String money = value.getString("money");
                        mPointsDetailsBean = new PointsDetailsBean(uid, create_time, wtype, remark, money);
                        PointsDetailsBeanListBean.add(mPointsDetailsBean);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (dpCode == 200) {

                    // mPdetailsAdapter = new PdetailsAdapter(getBaseContext().getApplicationContext(),PointsDetailsBeanListBean);
                    mPdetailsAdapter.notifyDataSetChanged();
                    //mListView.setAdapter(mPdetailsAdapter);
                }

                if (dpCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                } else {
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

                onLoadComplete();
            }
        });
    }
     private void intView() {

        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/on_day_detail");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("time", day);
        params.addBodyParameter("page_index", 1);
        params.addBodyParameter("page_size", 10);


        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {


                try {
                    JSONObject jsonObject = new JSONObject(result);
                    dpCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsonObjec = new JSONObject(data);
                        page_count = jsonObjec.optInt("page_count", 0);
                        page_index = jsonObjec.optInt("page_index", 0);
                        String income = jsonObjec.optString("income", "");
                        String expend = jsonObjec.optString("expend", "");

                        String time = jsonObjec.optString("time", "");
                        String str = time.substring(0, 4);
                        String str1 = time.substring(5, 7);
                        String str2 = time.substring(8, 10);
                        pd_time.setText(str + "年" + str1 + "月"+str2+"日");


                        Double a1 = Double.parseDouble(income);
                        DecimalFormat decimalFormatq = new DecimalFormat("0.00");
                        String b1 = decimalFormatq.format(a1);


                        Double a2 = Double.parseDouble(expend);
                        String b2 = decimalFormatq.format(a2);


                        pd_income.setText(b1 +"");
                        pd_expend.setText("积分兑换   "+b2 + "");

                    }
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String uid = value.getString("uid");
                        String create_time = value.getString("create_time");
                        String wtype = value.getString("wtype");
                        String remark = value.getString("remark");
                        String money = value.getString("money");
                        mPointsDetailsBean = new PointsDetailsBean(uid, create_time, wtype, remark, money);
                        PointsDetailsBeanListBean.add(mPointsDetailsBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (dpCode == 200) {
                    mPdetailsAdapter = new PdetailsAdapter(getBaseContext().getApplicationContext(), PointsDetailsBeanListBean);
                    mPdetailsAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mPdetailsAdapter);
                }

                if (dpCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                } else {


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (PointsDetailsBeanListBean.size() == 0) {
                    show_list_pd.setVisibility(View.VISIBLE);
                } else {
                    show_list_pd.setVisibility(View.GONE);
                }
            }
        });


    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.pd_back:
                finish();
                break;
            case R.id.pd_find:

                showPartShadow(v);

                // shoewtime();
                break;
        }
    }

    private void showPartShadow(final View v){
        if(popupView==null){
            popupView = (PDShadowPopupView) new XPopup.Builder(this)
                    .atView(v)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow() {
                            myFind.setText("完成");
                        }
                        @Override
                        public void onDismiss() {
                             myFind.setText("查询");
                            SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
                            int  t = sharedPreferences.getInt("points_type", 0);
                            if (t==0){
                                type="";
                               findTypt("");
                             }else if(t==1){
                                type="积分返现";
                                findTypt(type);
                            }else if(t==2){
                                type="服务商收益";
                                findTypt(type);
                            }else if (t==3){
                                type="消费收益";
                                findTypt(type);
                            }
                            else if (t==4){
                                type="推广收益";
                                findTypt(type);
                            }
                            else if (t==5){
                                type="积分兑换";
                                findTypt(type);
                            }
                            else if (t==6){
                                type="积分收益";
                                findTypt(type);
                            }
                            else if (t==7){
                                type="积分兑换";
                                findTypt(type);
                            }
                        }
                    })
                    .asCustom(new PDShadowPopupView(this));
        }

        popupView.show();
    }





    private void shoewtime() {
        DateScrollerDialog dialog = new DateScrollerDialog.Builder()
                .setType(Type.YEAR_MONTH)
                .setMinMilliseconds(System.currentTimeMillis() - HUNDRED_YEARS)
                .setMaxMilliseconds(System.currentTimeMillis())
                .setCurMilliseconds(mLastTime)
                .setCallback(mOnDateSetListener)
                .build();


        if (dialog != null) {
            if (!dialog.isAdded()) {
                dialog.show(getFragmentManager(), "year_month_day");
            }
        }


    }

    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }
    private void findTypt(String type) {
        PointsDetailsBeanListBean.clear();
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/on_day_detail");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("time", day);
        params.addBodyParameter("page_index", 1);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("type", type);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {


                try {
                    JSONObject jsonObject = new JSONObject(result);
                    dpCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsonObjec = new JSONObject(data);
                        page_count = jsonObjec.optInt("page_count", 0);
                        page_index = jsonObjec.optInt("page_index", 0);
                        String income = jsonObjec.optString("income", "");
                        String expend = jsonObjec.optString("expend", "");
                        Double a1 = Double.parseDouble(income);
                        DecimalFormat decimalFormatq = new DecimalFormat("0.00");
                        String b1 = decimalFormatq.format(a1);
                        Double a2 = Double.parseDouble(expend);
                        String b2 = decimalFormatq.format(a2);
                        pd_income.setText(b1 +"");
                        pd_expend.setText(b2 + "");
                    }
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String uid = value.getString("uid");
                        String create_time = value.getString("create_time");
                        String wtype = value.getString("wtype");
                        String remark = value.getString("remark");
                        String money = value.getString("money");
                        mPointsDetailsBean = new PointsDetailsBean(uid, create_time, wtype, remark, money);
                        PointsDetailsBeanListBean.add(mPointsDetailsBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (dpCode == 200) {
                    mPdetailsAdapter = new PdetailsAdapter(getBaseContext().getApplicationContext(), PointsDetailsBeanListBean);
                    mPdetailsAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mPdetailsAdapter);
                }

                if (dpCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                } else {


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
                if (PointsDetailsBeanListBean.size() == 0) {
                    show_list_pd.setVisibility(View.VISIBLE);
                } else {
                    show_list_pd.setVisibility(View.GONE);
                }
            }
        });


    }
}
